package com.ecjtu.stadiumre_servations.controller;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ecjtu.stadiumre_servations.config.AlipayConfig;
import com.ecjtu.stadiumre_servations.config.RabbitMQConfig;
import com.ecjtu.stadiumre_servations.entity.domain.Booking;
import com.ecjtu.stadiumre_servations.entity.domain.GroupActivity;
import com.ecjtu.stadiumre_servations.entity.domain.GroupMember;
import com.ecjtu.stadiumre_servations.entity.domain.GroupRecord;
import com.ecjtu.stadiumre_servations.mapper.BookingMapper;
import com.ecjtu.stadiumre_servations.mapper.GroupActivityMapper;
import com.ecjtu.stadiumre_servations.mapper.GroupMemberMapper;
import com.ecjtu.stadiumre_servations.mapper.GroupRecordMapper;
import com.ecjtu.stadiumre_servations.response.Result;
import com.ecjtu.stadiumre_servations.service.AlipayService;
import com.ecjtu.stadiumre_servations.service.BookingService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@RestController
public class AlipayController {
    @Autowired
    public AlipayService alipayService;
    @Autowired
    private BookingService bookingService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private GroupMemberMapper groupMemberMapper;
    @Autowired
    private GroupActivityMapper groupActivityMapper;
    @Autowired
    private BookingMapper bookingMapper;
    @Autowired
    private GroupRecordMapper groupRecordMapper;
    @RequestMapping("/pay")
    public void toAlipay(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String bookingId) throws IOException, IOException {
        // 根据预约编号查询预约信息
        Booking booking = bookingService.getById(bookingId);
        if (booking == null) {
            httpResponse.getWriter().write("预约信息不存在");
            System.out.println("null");
            return;
        }
        // 生成订单号
        String payId = bookingId;
        // 计算预约总价
        double price = booking.getBookingTotalPrice();
        String orderName = "场馆预约支付";
        String body = "场馆预约支付，预约编号：" + booking.getBookingId();
        Map<String, String> sourceMap = new HashMap<>();
        sourceMap.put("out_trade_no", payId);  // 订单号
        sourceMap.put("total_amount", String.valueOf(price));  // 总计
        sourceMap.put("body", body); // 描述
        sourceMap.put("order_name", orderName); // 订单名
        String form = alipayService.toAlipay(sourceMap);
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        try {
            rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
                    RabbitMQConfig.PAYMENT_REQUEST_ROUTING_KEY, sourceMap);
        } catch (Exception e) {
            LambdaUpdateWrapper<Booking> rollback = Wrappers.<Booking>lambdaUpdate()
                    .set(Booking::getBookingStatus, "已取消")
                    .eq(Booking::getBookingId, booking.getBookingId());
            bookingService.update(rollback);
        }
    }

    @PostMapping("/notify")
    public String alipayNotify(HttpServletRequest request) throws Exception {
        // 获取支付宝POST过来的反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        // 验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.CHARSET,
                AlipayConfig.SIGNTYPE);

        if (signVerified) {
            String tradeStatus = params.get("trade_status");
            String outTradeNo = params.get("out_trade_no");

            System.out.println(tradeStatus);
            System.out.println(outTradeNo);
            System.out.println("=====");
//            String userId = params.get("userId");
            switch (tradeStatus) {
                case "TRADE_SUCCESS":
                    // 发送支付成功消息到消息队列
                    Map<String, String> successMessage = new HashMap<>();
                    successMessage.put("out_trade_no", outTradeNo);
                    successMessage.put("trade_status", tradeStatus);
                    rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.PAYMENT_RESULT_ROUTING_KEY, successMessage);
                    break;
                case "TRADE_CLOSED":
                    // 超时  发送支付关闭消息到消息队列，更新预约状态为"已取消"
                    Map<String, String> closedMessage = new HashMap<>();
                    closedMessage.put("out_trade_no", outTradeNo);
                    closedMessage.put("trade_status", tradeStatus);
                    rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.PAYMENT_RESULT_ROUTING_KEY, closedMessage);
                    break;
                case "WAIT_BUYER_PAY":
                    // 等待支付，可记录日志
                    System.out.println("订单 " + outTradeNo + " 等待支付");
                    break;
//                default:
//                    // 其他状态处理
            }
            return "success";
        }
        return "fail";
    }
    @PostMapping("/process")
    public Result processRefund(@RequestBody  Map<String, String> refundParams) {
        try {
//            // 检查参数是否有效
//            if (refundParams.get("out_trade_no") == null || refundParams.get("refund_amount") == null) {
//                return Result.fail("退款失败：商户订单号或退款金额不能为空");
//            }

            // 调用退款服务
            String result = alipayService.refund(refundParams);

            // 根据退款结果返回相应信息
            if (result.contains("成功")) {
                return Result.ok(result);
            } else {
                return Result.fail(result);
            }
        } catch (Exception e) {
            // 记录异常信息
            e.printStackTrace();
            return Result.fail("退款处理异常，请稍后重试");
        }
    }
}